package pr.lanmu.service;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pr.lanmu.annotation.CustomLog;
import pr.lanmu.common.mapper.CronMapper;
import pr.lanmu.common.po.Cron;
import pr.lanmu.config.util.ConvertUtil;
import pr.lanmu.config.util.PageUtil;
import pr.lanmu.config.util.QuartzJob;
import pr.lanmu.config.util.Res;
import pr.lanmu.config.web.CustomPageInfo;
import pr.lanmu.controller.request.CronReq;
import pr.lanmu.controller.response.CronRes;

/**
 * 定时任务服务
 */
@Service
@CustomLog
@SuppressWarnings("all")
public class CronService {
    @Autowired
    private CronMapper cronMapper;
    @Autowired
    private QuartzJob quartzJob;

    /**
     * 查询定时任务
     */
    public Res<CustomPageInfo<CronRes.list>> list(CronReq.list param) {
        return Res.success(PageUtil.getPageInfo(QueryChain.of(Cron.class).orderBy(Cron::getId).desc().page(Page.of(param.getPageIndex(), param.getPageSize())), CronRes.list.class));
    }

    /**
     * 新增定时任务
     */
    public Res<?> post(CronReq.post param) {
        Cron cron = Cron.create();
        ConvertUtil.copy(param, cron).save();
        quartzJob.loadJob(cron);
        return Res.success();
    }

    /**
     * 删除定时任务
     */
    public Res<?> delete(CronReq.delete param) {
        Long id = param.getId();
        Cron.create().setId(id).oneByIdOpt().ifPresent(cron -> {
            quartzJob.removeJob(cron);
            cronMapper.deleteById(id);
        });
        return Res.success();
    }

    /**
     * 修改定时任务
     */
    public Res<?> put(CronReq.put param) {
        Long id = param.getId();
        Cron.create().setId(id).oneByIdOpt().ifPresent(cron -> {
            quartzJob.removeJob(cron);
        });
        Cron cron = Cron.create();
        ConvertUtil.copy(param, cron).updateById();
        quartzJob.loadJob(cron);
        return Res.success();
    }

    public Res<?> loads(CronReq.loads param) {
        return Res.success(quartzJob.getAllTimer());
    }
}